package functions

import (
	"encoding/json"

	"github.com/project-flogo/core/data/coerce"

	"github.com/project-flogo/core/data"
	"github.com/project-flogo/core/data/expression/function"
)

func init() {
	err := function.Register(&fnUnmarshalJSONObject{})
	if err != nil {
		panic(err)
	}
	err = function.Register(&fnUnmarshalJSONArray{})
	if err != nil {
		panic(err)
	}
}

type fnUnmarshalJSONObject struct{}

func (fnUnmarshalJSONObject) Name() string {
	return "unmarshalJSONObject"
}

func (fnUnmarshalJSONObject) Sig() (paramsTypes []data.Type, isVariadic bool) {
	return []data.Type{data.TypeBytes}, false
}

func (fnUnmarshalJSONObject) Eval(params ...interface{}) (interface{}, error) {
	data := params[0]
	bytes, err := coerce.ToBytes(data)
	if err != nil {
		return nil, err
	}
	m := map[string]interface{}{}
	err = json.Unmarshal(bytes, &m)
	return m, err
}

type fnUnmarshalJSONArray struct{}

func (fnUnmarshalJSONArray) Name() string {
	return "unmarshalJSONArray"
}

func (fnUnmarshalJSONArray) Sig() (paramsTypes []data.Type, isVariadic bool) {
	return []data.Type{data.TypeBytes}, false
}

func (fnUnmarshalJSONArray) Eval(params ...interface{}) (interface{}, error) {
	data := params[0]
	bytes, err := coerce.ToBytes(data)
	if err != nil {
		return nil, err
	}
	arr := []interface{}{}
	err = json.Unmarshal(bytes, &arr)
	return arr, err
}
